from urllib import request,parse
import hashlib
import random
import time
import json
import requests
 
 
def translate(content):
    url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'
    client = 'fanyideskweb'

    salt = int(time.time()*1000) + random.randint(1,10)

    key = 'sr_3(QOHT)L2dx#uuGR@r'
     
    sign = hashlib.md5((client + content + str(salt) + key).encode('utf-8')).hexdigest()
    # 定义请求的参数，并编码转换
    data={
	    "i": content,
	    "from": "AUTO",
	    "to": "AUTO",
	    "smartresult": "dict",
	    "client": "fanyideskweb",
	    "salt": salt,
	    "sign": sign,
	    "doctype": "json",
	    "version": "2.1",
	    "keyfrom": "fanyi.web",
	    "action": "FY_BY_REALTIME",
	    "typoResult": "false",

    }
    data = parse.urlencode(data)
    #设置hearders头信息
    headers = {
	    "Accept": "application/json, text/javascript, */*; q=0.01",
	    
	    "Accept-Language": "zh-CN,zh;q=0.9",
	    "Connection": "keep-alive",
	    "Content-Length": len(data),
	    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
	    "Cookie": "OUTFOX_SEARCH_USER_ID=161139380@111.202.28.98; OUTFOX_SEARCH_USER_ID_NCOO=1362721219.3073304; JSESSIONID=aaa6LYGFwMOfFbUdgQuDw; ___rl__test__cookies=1543316222239",
	    "Host": "fanyi.youdao.com",
	    "Origin": "http://fanyi.youdao.com",
	    "Referer": "http://fanyi.youdao.com/",
	    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36",
	    "X-Requested-With": "XMLHttpRequest"
    }

    #创建请求，发送请求，爬取信息
    req = request.Request(url,data=bytes(data,encoding='utf-8'),headers=headers)
    res = request.urlopen(req)
    # 解析结果
    html = res.read().decode('utf-8')
    result_dict = json.loads(html)
    
    print(result_dict['translateResult'][0][0]['tgt'])
def youdaoTranslate(value):
    
        # Request URL
        responseURL = 'http://fanyi.youdao.com/translate?smartresult=dict&smartresult=rule'
        # 待提交准备Post给url的Data:定义为dict
        form_Data = {}
        form_Data['i'] = value
        form_Data['from'] = 'AUTO'
        form_Data['to'] = 'AUTO'
        form_Data['smartresult'] = 'dict'
        form_Data['client'] = 'fanyideskweb'
        form_Data['doctype'] = 'json'
        form_Data['version'] = '2.1'
        form_Data['keyfrom'] = 'fanyi.web'
        form_Data['action'] = 'FY_BY_REALTIME'
        form_Data['typoResult'] = 'false'
        # 使用urlencode方法转换标准格式　
        r = requests.post(responseURL, data = form_Data)
        result = r.json()
        # 使用JSON
        # 找到翻译结果
        # 这里推荐一个格式化JSON的好工具：https://c.runoob.com/front-end/53
        translate_result_main = result['translateResult'][0][0]['tgt']
        # 打印翻译结果
        print(translate_result_main)
        return True

if __name__ == '__main__':
    print("{}{:<15}{:<}".format("","1.urllib爬取","2.requests爬取"))
    print("=" * 38)
    key = input("请输入对应的选择: ")
    #根据键盘值判断，并执行对应的操作
    if key == "1":
        print("=" * 12, "urllib爬取", "=" * 12)
        print("")
        while True:
            content = input("请输入您需要翻译的内容:\n")
            print("-" * 38)
            translate(content)
            print("-" * 38)
            print("")
            if content == "q":
                break
    if key == "2":
        print("=" * 12, "requests爬取", "=" * 12)
        print("")
        while True:
            word = input("请输入您需要翻译的内容:\n")
            print("-" * 38)
            youdaoTranslate(word)
            print("-" * 38)
            print("")
            if word == "q":
                break
